package com.centaline.androidsalesblog.activities.newest;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatTextView;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewStub;
import android.widget.ImageView;

import com.android.volley.VolleyError;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.activities.mine.LoginActivity;
import com.centaline.androidsalesblog.api.newest.NewEstActDetailApi;
import com.centaline.androidsalesblog.api.newest.NewPropPhoneApi;
import com.centaline.androidsalesblog.api.newest.NewPropStaffApi;
import com.centaline.androidsalesblog.base.BaseActivity;
import com.centaline.androidsalesblog.constants.AppConstant;
import com.centaline.androidsalesblog.constants.AppNameType;
import com.centaline.androidsalesblog.constants.CommonConstant;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.constants.SourceType;
import com.centaline.androidsalesblog.constants.SprfConstant;
import com.centaline.androidsalesblog.events.MineInfoUpdate;
import com.centaline.androidsalesblog.model.businissobject.CollectInfoBo;
import com.centaline.androidsalesblog.model.businissobject.NewPropImgBo;
import com.centaline.androidsalesblog.model.businissobject.NewPropPhoneBo;
import com.centaline.androidsalesblog.model.businissobject.NewPropStaffBo;
import com.centaline.androidsalesblog.model.databaseobject.BizUnitDo;
import com.centaline.androidsalesblog.model.databaseobject.NewEstActDo;
import com.centaline.androidsalesblog.model.responseobject.CollectInfoListRo;
import com.centaline.androidsalesblog.model.responseobject.NewEstActDetailRo;
import com.centaline.androidsalesblog.model.responseobject.NewPropPhoneRo;
import com.centaline.androidsalesblog.model.responseobject.NewPropStaffListRo;
import com.centaline.androidsalesblog.model.responseobject.SimpleUserCenterRo;
import com.centaline.androidsalesblog.rx.database.RxDataBase;
import com.centaline.androidsalesblog.rx.request.RxRequest;
import com.centaline.androidsalesblog.utils.ContactUtil;
import com.centaline.androidsalesblog.utils.DateUtil;
import com.centaline.androidsalesblog.widgets.CollectView;
import com.centaline.androidsalesblog.widgets.MLoadView;
import com.centanet.framework.glide.GlideLoad;
import com.centanet.framework.interfaces.IResponseListener;
import com.centanet.framework.utils.SprfUtil;
import com.centanet.framework.widget.AbstractLoadView;
import com.trello.rxlifecycle.ActivityEvent;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Locale;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 活动详情
 * Created by guilin on 16/2/26.
 */
public class NewEstActDetailActivity extends BaseActivity implements View.OnClickListener {

    public static final int REQ_BOOK = 100;//报名

    private MLoadView mLoadView;
    private ImageView img_logo;
    private AppCompatTextView atv_title, atv_book_num, atv_act_date, atv_desc, atv_book_date,
            atv_book_address;
    private ViewStub vs_phone;
    private CollectView collectView;

    private NewEstActDetailApi newEstActDetailApi;
    private NewPropStaffApi newPropStaffApi;
    private NewPropPhoneApi newPropPhoneApi;
    private NewEstActDo newEstActDo;
    private String actId;
    private String newPropImg;
    private NewPropPhoneBo newPropPhoneBo;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_new_est_act_detail;
    }

    @Override
    protected void findViews() {
        setUniversalToolbar(R.string.title_new_est_act_detail);
        mLoadView = (MLoadView) findViewById(R.id.mLoadView);
        img_logo = (ImageView) findViewById(R.id.img_logo);
        atv_title = (AppCompatTextView) findViewById(R.id.atv_title);
        atv_book_num = (AppCompatTextView) findViewById(R.id.atv_book_num);
        atv_act_date = (AppCompatTextView) findViewById(R.id.atv_act_date);
        atv_desc = (AppCompatTextView) findViewById(R.id.atv_desc);
        atv_book_date = (AppCompatTextView) findViewById(R.id.atv_book_date);
        atv_book_address = (AppCompatTextView) findViewById(R.id.atv_book_address);
        vs_phone = (ViewStub) findViewById(R.id.vs_phone);
        collectView = (CollectView) findViewById(R.id.collectView);
    }

    @Override
    protected void initViews() {
        mLoadView.setLoadStatusListener(new AbstractLoadView.LoadStatusListener() {
            @Override
            public void load() {
                request();
            }
        });
        actId = getIntent().getStringExtra(ExtraConstant.NewEstActId);
        newEstActDetailApi = new NewEstActDetailApi(NewEstActDetailActivity.class, NewEstActDetailRo.class,
                actId, new IResponseListener<NewEstActDetailRo>() {
            @Override
            public void onResponse(NewEstActDetailRo newEstActDetailRo) {
                mLoadView.loadSuccess();
                newEstActDo = newEstActDetailRo.getNewEstActDo();
                if (newEstActDo != null) {
                    ArrayList<NewPropImgBo> newPropImgBos = newEstActDo.getNewPropImgBos();
                    NewPropImgBo newPropImgBo = newPropImgBos == null || newPropImgBos.size() == 0 ?
                            null : newPropImgBos.get(0);
                    if (newPropImgBo != null &&
                            !TextUtils.isEmpty(newPropImgBo.getFileUrl())) {
                        String imgAddress = newPropImgBo.getFileUrl();
                        imgAddress = imgAddress.contains(".") ? imgAddress.replace(".",
                                String.format(Locale.CHINA, "_%dx%d_f.",
                                        newPropImgBo.getWidth(),
                                        newPropImgBo.getHeight())) : "";
                        newEstActDo.setFileUrl(newPropImgBo.getFileUrl());
                        GlideLoad.load(new GlideLoad.Builder(GlideLoad.init(NewEstActDetailActivity.this)
                                , String.format(Locale.CHINA, "%s%s", newPropImg, imgAddress))
                                .placeHolder(R.drawable.ic_banner)
                                .error(R.drawable.ic_banner)
                                .openWifiSwitch()
                                .into(img_logo));
                        img_logo.setVisibility(View.VISIBLE);
                    }
                    atv_title.setText(newEstActDo.getActTitle());
                    atv_book_num.setText(String.valueOf(newEstActDo.getShowBookCnt()));
                    atv_act_date.setText(Html.fromHtml(DateUtil.getRemainTime(newEstActDo.getEndDate())));
                    atv_desc.setText(newEstActDo.getDescription());
                    atv_book_date.setText(String.format("%s-%s",
                            DateUtil.format(newEstActDo.getStartDate(), DateUtil.FORMAT2, "yyyy年MM月dd日"),
                            DateUtil.format(newEstActDo.getEndDate(), DateUtil.FORMAT2, "yyyy年MM月dd日")));
                    atv_book_address.setText(newEstActDo.getActAddress());

                    newPropPhoneApi.setTargetValue(newEstActDo.getEstExtId());
                    newPropStaffApi.setEstExtId(newEstActDo.getEstExtId());
                    newPropStaffApi.startRequest();

                    collectStatus();

                    RxDataBase.fpHistorySave(4, actId, newEstActDo)
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .compose(NewEstActDetailActivity.this.<Void>bindUntilEvent(ActivityEvent.DESTROY))
                            .subscribe(new Action1<Void>() {
                                @Override
                                public void call(Void aVoid) {

                                }
                            });
                }
            }

            @Override
            public void onErrorResponse(VolleyError error) {
                mLoadView.loadError();
            }
        });

        newPropStaffApi = new NewPropStaffApi(NewEstActDetailActivity.class, NewPropStaffListRo.class, new IResponseListener<NewPropStaffListRo>() {

            @Override
            public void onResponse(NewPropStaffListRo newPropStaffListRo) {
                final ArrayList<NewPropStaffBo> newPropStaffBos = newPropStaffListRo.getNewPropStaffBos();
                if (newPropStaffBos != null && newPropStaffBos.size() > 0) {
                    newPropPhoneApi.setStaffNos(newPropStaffBos.get(0).getStaffNo());
                    newPropPhoneApi.startRequest();
                }
            }

            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        newPropPhoneApi = new NewPropPhoneApi(NewEstActDetailActivity.class, NewPropPhoneRo.class, new IResponseListener<NewPropPhoneRo>() {
            @Override
            public void onResponse(NewPropPhoneRo newPropPhoneRo) {
                if (newPropPhoneRo.getNewPropPhoneBos() == null ||
                        newPropPhoneRo.getNewPropPhoneBos().size() == 0)
                    return;
                newPropPhoneBo = newPropPhoneRo.getNewPropPhoneBos().get(0);
                if (newPropPhoneBo != null &&
                        vs_phone != null) {
                    vs_phone.inflate();
                    AppCompatTextView atv_phone = (AppCompatTextView) findViewById(R.id.atv_phone);
                    String bigCode = newPropPhoneBo.getBigCode();
                    String extCode = newPropPhoneBo.getExtCode();
                    if (atv_phone != null &&
                            !TextUtils.isEmpty(bigCode) &&
                            !TextUtils.isEmpty(newPropPhoneBo.getExtCode())) {
                        if (TextUtils.getTrimmedLength(bigCode) == 10) {
                            atv_phone.setText(String.format(Locale.CHINA, "%s-%s-%s转%s",
                                    bigCode.substring(0, 3),
                                    bigCode.substring(3, 6),
                                    bigCode.substring(6, 10),
                                    newPropPhoneBo.getExtCode()));
                        } else {
                            atv_phone.setText(String.format(Locale.CHINA, "%s-%s",
                                    bigCode,
                                    extCode));
                        }
                    }
                }
            }

            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        bizUnit();
    }

    private void request() {
        newEstActDetailApi.startRequest();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_call:
                if (newPropPhoneBo != null) {
                    new AlertDialog.Builder(this)
                            .setMessage(String.format(Locale.CHINA, "拨打:%s,%s",
                                    newPropPhoneBo.getBigCode(), newPropPhoneBo.getExtCode()))
                            .setPositiveButton("拨打", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    ContactUtil.dial(NewEstActDetailActivity.this, newPropPhoneBo.getBigCode(), newPropPhoneBo.getExtCode());
                                }
                            }).setNegativeButton("取消", null)
                            .create()
                            .show();
                }
                break;
            case R.id.collectView:
                collect();
                break;
            case R.id.btn_book:
                startActivityForResult(new Intent(this, NewPropActBookActivity.class)
                                .putExtra(ExtraConstant.NewEstActObject, newEstActDo)
                        , REQ_BOOK);
                break;
            default:
                break;
        }
    }

    private void collect() {
        if (AppConstant.IsLogin) {
            if (collectView.isCollect()) {
                RxRequest.cancelCollect(NewEstActDetailActivity.class, collectView.getCollectId())
                        .compose(this.<SimpleUserCenterRo>bindUntilEvent(ActivityEvent.DESTROY))
                        .subscribe(new Action1<SimpleUserCenterRo>() {
                            @Override
                            public void call(SimpleUserCenterRo simpleUserCenterRo) {
                                if (0 == simpleUserCenterRo.getResultNo()) {
                                    collectView.setCollect(false);
                                    EventBus.getDefault().post(new MineInfoUpdate(15));
                                    snack(R.string.collect_cancel);
                                } else {
                                    snack(simpleUserCenterRo.getMessage());
                                }
                            }
                        }, new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                netWorkUnable();
                            }
                        });
            } else {
                RxRequest.addCollect(NewEstActDetailActivity.class, AppNameType.NEWPROP, SourceType.HUODONG, collectView.getCollectId(), actId,
                        String.format(Locale.CHINA, "%s%s?ActId=%s", AppConstant.NewEstUrl, "BookingActivityRequest", actId))
                        .compose(this.<SimpleUserCenterRo>bindUntilEvent(ActivityEvent.DESTROY))
                        .subscribe(new Action1<SimpleUserCenterRo>() {
                            @Override
                            public void call(SimpleUserCenterRo simpleUserCenterRo) {
                                if (0 == simpleUserCenterRo.getResultNo()) {
                                    EventBus.getDefault().post(new MineInfoUpdate(15));
                                    collectView.setCollect(true);
                                    if (0 != simpleUserCenterRo.getResult()) {
                                        collectView.setCollectId(String.valueOf(simpleUserCenterRo.getResult()));
                                    }
                                    SprfUtil.setInt(NewEstActDetailActivity.this,
                                            String.format("%s_%s", SprfConstant.COLLECT_POSITION, AppConstant.CityCode), 15);
                                    snack(R.string.collect_success);
                                } else {
                                    snack(simpleUserCenterRo.getMessage());
                                    collectStatus();
                                }
                            }
                        }, new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                netWorkUnable();
                            }
                        });
            }
        } else {
            startActivityForResult(new Intent(this, LoginActivity.class), CommonConstant.REQ_COLLECT);
        }
    }

    /**
     * 收藏状态
     */
    private void collectStatus() {
        if (AppConstant.IsLogin) {
            RxRequest.collectStatus(NewEstActDetailActivity.class, actId,
                    String.format(Locale.CHINA, "%s%s?ActId=%s", AppConstant.NewEstUrl, "BookingActivityRequest", actId))
                    .compose(this.<CollectInfoListRo>bindUntilEvent(ActivityEvent.DESTROY))
                    .subscribe(new Action1<CollectInfoListRo>() {
                        @Override
                        public void call(CollectInfoListRo collectInfoListRo) {
                            final ArrayList<CollectInfoBo> temp = collectInfoListRo.getList();
                            if (temp != null &&
                                    temp.size() > 0) {
                                collectView.setCollectId(String.valueOf(temp.get(0).getCollectID()));
                                collectView.setCollect(!temp.get(0).isDel());
                            } else {
                                collectView.setCollect(false);
                            }
                        }
                    });
        }
    }

    /**
     * 获取配置
     */
    private void bizUnit() {
        RxDataBase.getBizUnit()
                .compose(this.<BizUnitDo>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<BizUnitDo>() {
                    @Override
                    public void call(BizUnitDo bizUnitDo) {
                        newPropImg = bizUnitDo.getNewpropimg();
                        request();
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CommonConstant.REQ_COLLECT:
                    collect();
                    break;
                case REQ_BOOK:
                    atv_book_num.setText(String.valueOf(newEstActDo.getShowBookCnt() + 1));
                    EventBus.getDefault().post(new MineInfoUpdate(2));
                    break;
                default:
                    break;
            }
        }
    }
}
